import React, {Component} from 'react';
import SshInput from '../../base/SshInput'
import SshForm from '../../base/SshForm'
import SshButton from '../../base/SshButton'

const usernameRule = [
    {required: true, message: '用户名不能为空'},
    {
        validator: (value, callBack) => {
            setTimeout(() => {
                if (value.length > 6) {
                    callBack(new Error('用户名长度不能超过6'))
                } else {
                    callBack()
                }
            }, 500)

        }
    }
]

const contentRule = [
    {required: true, message: '评论不能为空'}
]

class CommentInput extends Component {
    constructor() {
        super()
        this.state = {
            isError: false,
            commentForm: {
                username: '',
                content: ''
            }
        }
    }

    onTextChange = (value) => {
        this.setState({
            commentForm: {
                ...this.state.commentForm,
                content: value
            }
        })
    }

    onUsernameChange = (value) => {
        this.setState({
            commentForm: {
                ...this.state.commentForm,
                username: value
            }
        })
    }

    reset = () => {
        this.setState({
            commentForm: {
                ...this.state.commentForm,
                content: ''
            }
        })
        this.commentForm.clearValid()
    }

    submit = () => {
        this.commentForm.valid(() => {
            const onSubmit = this.props.onSubmit
            onSubmit(this.state.commentForm)
            this.reset()
        })
    }


    render() {
        const state = this.state

        const {commentForm} = state

        const {reset, submit} = this

        return (
            <div>
                <SshForm ref={ref => this.commentForm = ref}>
                    <SshInput
                        value={commentForm.username}
                        rules={usernameRule}
                        onChange={this.onUsernameChange}
                        className="Comment-input"
                        placeholder="请输入用户名"/>
                    <SshInput
                        value={commentForm.content}
                        rules={contentRule}
                        type="textarea"
                        onChange={this.onTextChange}
                        className="Comment-text"
                        placeholder="请输入评论"/>
                </SshForm>
                <div className="Comment-btn-wrapper">
                    <SshButton className="Comment-btn" onClick={submit}>发表</SshButton>
                    <SshButton className="Comment-btn" onClick={reset}>重置</SshButton>
                </div>
            </div>
        )
    }
}

export default CommentInput